package com.suxin.thread;

import java.io.Serializable;

/**
 * @author Tang
 * @classname ConcurrencyThrottleSupport
 * @description [ 这是一个限流的类 ]
 * @date 2022/12/30 16:01
 */
public abstract class ConcurrencyThrottleSupport implements Serializable {

    private final int UNBOUND_CONCURRENT = -1;

    private final transient Object monitor = new Object();

    private int concurrentLimit = UNBOUND_CONCURRENT;

    private int concurrentCount = 0;

    public ConcurrencyThrottleSupport(int concurrentLimit) {
        this.concurrentLimit = concurrentLimit;
    }

    protected void beforeAccess() {
        if (concurrentLimit == UNBOUND_CONCURRENT) {
            return;
        }
        synchronized (monitor) {
            // 总次数 》 限流次数
            if (concurrentCount >= concurrentLimit) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                this.concurrentCount++;
            }
        }
    }

    protected void afterAccess() {
        if (concurrentLimit > 0) {
            synchronized (monitor) {
                this.concurrentCount--;
                this.notify();
            }
        }
    }


}